import sys
import wx

from time import time
from LMG.Utility.scrape import ScrapeThread
from LMG.Utility.constants import *

"""
Access to basic torrent actions
Features:
 - scrape
 - pause
 - pauseResume
 - stop
 - queue
 - resume
 - hashCheck
"""

################################################################

class TorrentActions:
    """
    Handles processing of most all the user-initiated actions
    on a torrent.
    """
    def __init__(self, torrent):
        self.torrent = torrent
        
        self.lastgetscrape = 0
        self.oldstatus = None
    
    def scrape(self, faildialog = False, manualscrape = False, interval = 20):
        # Manual Scraping should be done no more than once per minute
        if (manualscrape):
            if (time() - self.lastgetscrape < 60):
                if faildialog:
                    dlg = wx.MessageDialog(None, _('Please wait at least 1 minute before scraping again'), _('Error'), wx.ICON_ERROR)
                    dlg.ShowModal()
                    dlg.Destroy()
                return False
        # Automatic Scraping can be done only after %interval% minutes
        elif (self.lastgetscrape != 0) and ((time() - self.lastgetscrape) < (interval*60)):
            # Scraping again too soon
            return False

        ScrapeThread(self.torrent, manualscrape).start()
        
        self.lastgetscrape = time()
        
        return True

    def pause(self, release = False):
        """
        pause a torrent or release it,
        returns True if we actually did something
        """
        torrent = self.torrent
        
        # We need to release the torrent
        if release:
            return self.pauseResume()
        
        # Pause the torrent if it isn't already paused or queued
        if torrent.status.value == STATUS_PAUSE or not torrent.status.isActive():
            return False

        self.oldstatus = torrent.status.value

        torrent.status.updateStatus(STATUS_PAUSE)

        if torrent.status.isActive():
            torrent.connection.engine.dow.Pause()

        torrent.updateSingleItemStatus()
        return True
        
    def pauseResume(self):
        """
        Resumes paused torrent
        """
        torrent = self.torrent
        
        if torrent.status.value != STATUS_PAUSE:
            return False

        torrent.status.updateStatus(self.oldstatus)

        # pause an active process
        ###########################################
        if torrent.status.isActive():
            torrent.connection.engine.dow.Unpause()
            return True

        return False

    def stop(self):
        """
        Stop a single torrent,
        returns True if we actually did something
        """
        torrent = self.torrent

        torrent.status.autostarted = False
        torrent.status.forced = False
        
        if torrent.status.isDoneUploading():
            return True
        
        if torrent.status.value == STATUS_STOP:
            return False
        
        torrent.connection.stopEngine(update = False)
        
        torrent.status.updateStatus(STATUS_STOP)
        
        torrent.updateSingleItemStatus()
                
        return True
        
    def queue(self):
        """
        Return True if we put something into queue
        """
        torrent = self.torrent

        torrent.status.autostarted = False
        torrent.status.forced = False

        if torrent.status.isDoneUploading():
            # Might need to return True to show something happened
            return True

        # Do nothing if already queued, stopped, or done uploading
        if torrent.status.value == STATUS_QUEUE:
            return False
        
        torrent.connection.stopEngine(update = False)
        
        torrent.status.updateStatus(STATUS_QUEUE)
        
        torrent.updateSingleItemStatus()
        
        return True

    def resume(self, skipcheck = False):
        """
        Resume a torrent
        """
        torrent = self.torrent
        
        torrent.status.autostarted = False
        
        ################### Resume for On-Hold State ###########################
        if torrent.status.value == STATUS_PAUSE:
            return self.pauseResume()

        ################## Resume for Other inactive States ##############################
        
        # Don't resume if currently active       
        if torrent.status.isActive():
            return False
        
        # Don't resume if done uploading unless the user really wants to
        if torrent.status.isDoneUploading():
            if not torrent.dialogs.resumeCompleted():
                return True
            torrent.status.forced = True
        
        torrent.status.updateStatus(STATUS_QUEUE)
        
        torrent.connection.startEngine()
        
        return True

    def hashCheck(self):
        """
        Force a hashcheck for a torrent.
        """
        torrent = self.torrent
        
        torrent.status.autostarted = False
        torrent.status.forced = False
        
        # Don't need to do hashcheck if already checking
        if torrent.status.value == STATUS_HASHCHECK:
            return False

        self.oldstatus = torrent.status.value
        
        torrent.connection.stopEngine()
        
        torrent.connection.startEngine(STATUS_HASHCHECK)

        return True

        
